package com.gogowan.agroenterprise.contorl;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.utils.Utils;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" })
public class FtpUpload {
	public static String TAG = FtpUpload.class.getName();

	// public static String FTP_SERVER="file.i-oid.org.cn" ;192.168.2.203
	public static String FTP_SERVER = "192.168.2.203";
	// public static String FTP_NAME="ncp1";
	// public static String FTP_PWD="ncp1!@#398019";
	/*
	 * public static String IMAGE_FILE ="" ; public static String VIDOE_FILE =
	 * "";
	 */

	private Context context;
	private FTPClient ftp;
	private ProgressDialog progressDialog;
	private SharedPreferences preferences;
	private String domainName = null;
	private String name = null;
	private String pwd = null;
	private String dirFileName;

	/**
	 * 创建ftp连接，并指定文件夹
	 * 
	 * @param dirFileName
	 * @param system
	 *            1为农产品种植巡检 2为供求发布模块
	 * @throws Exception
	 */
	public FtpUpload(Context context, String dirFileName, int system) {
		this.context = context;
		this.dirFileName = dirFileName;

		preferences = context.getSharedPreferences("LoginINfo", 0);
		
		//LoginResultInfo loginResultInfo = (LoginResultInfo) Utils.fromJSON(
				//string, LoginResultInfo.class);

//		if (system == 1) {
//			domainName = loginResultInfo.getFtpulr();
//			name = loginResultInfo.getFtpusername();
//			pwd = loginResultInfo.getFtppwd();
//		} else if (system == 2) {
//			domainName = loginResultInfo.getYxftpulr();
//			name = loginResultInfo.getYxftpusername();
//			pwd = loginResultInfo.getYxftppwd();
//		}

		ftp = new FTPClient();
		try {

			ftp.connect("61.55.142.65");
			// ftp.connect(domainName);
			// Log.d("H3c", ftp.toString());
			ftp.login(name, pwd);

			ftp.setType(FTPClient.TYPE_AUTO);
			ftp.setCharset("utf8");

			// new Thread(runnable).start();

			boolean isCunzai = false;

			String[] list = null;
			try {
				list = ftp.listNames();
			} catch (FTPDataTransferException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FTPAbortedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FTPListParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (String string1 : list) {
				// Log.d("H3c", file.getName());
				if (dirFileName.equals(string1)) {
					isCunzai = true;
				}
			}

			Log.d("currentDirectory", ftp.currentDirectory());
			// 是不是在该文件夹下
			if (!isCunzai) {
				// 不存在该目录，则创建目录
				ftp.createDirectory(dirFileName);
			}
			// 改变路径
			ftp.changeDirectory(dirFileName);
			initProgress();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FTPIllegalReplyException e) {
			e.printStackTrace();
		} catch (FTPException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 改变路径
	 * 
	 * @param dirFileName
	 */
	public void changeDirectory(String dirFileName) throws Exception {
		try {
			ftp.changeDirectory(dirFileName);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FTPIllegalReplyException e) {
			e.printStackTrace();
		} catch (FTPException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化进度条
	 */
	public void initProgress() {
		progressDialog = new ProgressDialog(context);
		// 设置进度条风格，风格为圆形，旋转的
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// 设置ProgressDialog 标题
		progressDialog.setTitle("文件上传");
		// 设置ProgressDialog提示信息
		// progressDialog.setMessage("文件");
		// 设置ProgressDialog标题图标
		// progressDialog.setIcon(R.drawable.img2);
		// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
		progressDialog.setIndeterminate(false);
		// 设置ProgressDialog 进度条进度
		progressDialog.setProgress(100);
		// 设置ProgressDialog 是否可以按退回键取消
		progressDialog.setCancelable(false);
		// 让ProgressDialog显示
		progressDialog.show();
	}

	/**
	 * 关闭FTP连接，关闭时候像服务器发送一条关闭命令
	 * 
	 * @param client
	 *            FTP客户端
	 * @return 关闭成功，或者链接已断开，或者链接为null时候返回true，通过两次关闭都失败时候返回false
	 */
	public static boolean closeConnection(FTPClient client) {
		if (client == null)
			return true;
		if (client.isConnected()) {
			try {
				client.disconnect(true);
				return true;
			} catch (Exception e) {
				try {
					client.disconnect(false);
				} catch (Exception e1) {
					e1.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 关闭ftp
	 */
	public boolean close() {
		// progressDialog.cancel();
		try {
			progressDialog.cancel();
			progressDialog.dismiss();
			if (ftp.isConnected()) {
				// ftp.logout();
				ftp.disconnect(true);
				return true;
			}
		} catch (IllegalStateException e) {
			progressDialog.cancel();
			progressDialog.dismiss();
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			progressDialog.cancel();
			progressDialog.dismiss();
			e.printStackTrace();
			return false;
		} catch (FTPIllegalReplyException e) {
			progressDialog.cancel();
			progressDialog.dismiss();
			e.printStackTrace();
			return false;
		} catch (FTPException e) {
			progressDialog.cancel();
			progressDialog.dismiss();
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			try {
				ftp.disconnect(false);
			} catch (Exception e1) {
				e1.printStackTrace();
				return false;
			}
			progressDialog.cancel();
			progressDialog.dismiss();
			e.printStackTrace();
			return false;
		}
		return true;
	}

	int fileLength = 0;

	/**
	 * 上传文件
	 * 
	 * @param fileDir
	 * @return
	 */
	public void ftpUpload(String fileDir) throws Exception {
		try {
			if (ftp.isConnected()) {
				File uploadFile = new File(fileDir);
				Log.i("=====================uploadFile================", ""
						+ uploadFile.length());
				this.fileLength = (int) uploadFile.length();
				// listener.transferred(0);
				ftp.upload(uploadFile, listener);
			}
		} catch (Exception e) {
			close();
		}
		// } catch (IllegalStateException e) {
		// Log.d("H3c", "IllegalStateException");
		// e.printStackTrace();
		// } catch (IOException e) {
		// Log.d("H3c", "IOException");
		// e.printStackTrace();
		// } catch (FTPIllegalReplyException e) {
		// Log.d("H3c", "FTPIllegalReplyException");
		// e.printStackTrace();
		// } catch (FTPException e) {
		// Log.d("H3c", "FTPException");
		// e.printStackTrace();
		// } catch (FTPDataTransferException e) {
		// Log.d("H3c", "FTPDataTransferException");
		// e.printStackTrace();
		// } catch (FTPAbortedException e) {
		// Log.d("H3c", "FTPAbortedException");
		// e.printStackTrace();
		// }
		// return ftpFile;
	}

	private FTPDataTransferListener listener = new FTPDataTransferListener() {
		private int currentLength;

		// 传输放弃时触发
		@Override
		public void aborted() {
			Log.d(TAG, "aborted");
			try {
				if (!close()) {
					Toast.makeText(context, "传输失败", Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 文件传输完成时，触发
		@Override
		public void completed() {
			Log.d(TAG, "completed");
		}

		// 传输失败时触发
		@Override
		public void failed() {
			Log.d(TAG, "failed");
			Toast.makeText(context, "传输失败", Toast.LENGTH_SHORT).show();
			try {
				if (!close()) {
					Toast.makeText(context, "传输失败", Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 文件开始上传或下载时触发
		@Override
		public void started() {
			Log.d(TAG, "started");
			currentLength = 0;
			progressDialog.setProgress(0);
		}

		// 显示已经传输的字节数
		@Override
		public void transferred(int arg0) {
			Log.d(TAG, "transferred" + arg0);
			currentLength += arg0;
			double rat1 = (currentLength * 1.0) / (fileLength * 1.0) * 100;
			progressDialog.setProgress((int) rat1);
		}

	};

	/**
	 * 文件名
	 * 
	 * @param ext
	 * @return
	 */
	public static String getMediaFileName(String ext) {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmsssSSS");
		return dateFormat.format(date);
	}

	/**
	 * 保存文件路径
	 * 
	 * @param ext
	 * @return
	 */
	public static Uri getOutputMediaFileUri(String ext) {
		File imagesFolder = new File(Environment.getExternalStorageDirectory()
				+ "/DCIM/Camera/");
		imagesFolder.mkdirs();
		File image = new File(getMediaFileName(ext));
		Uri uri = Uri.fromFile(image);
		// Log.d(TAG,
		// "imagesFolder:"+imagesFolder.getAbsolutePath()+" uri:"+uri);
		return uri;
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.i("mylog", "请求结果为-->" + "000000000000000000000");
		}
	};

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			//
			// TODO: http request.
			//
			Message msg = new Message();
			try {
				ftp.connect(domainName);
				ftp.login(name, pwd);

				ftp.setType(FTPClient.TYPE_AUTO);
				ftp.setCharset("utf8");

				boolean isCunzai = false;

				String[] list = null;
				try {
					list = ftp.listNames();
				} catch (FTPDataTransferException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FTPAbortedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FTPListParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				for (String string1 : list) {
					// Log.d("H3c", file.getName());
					if (dirFileName.equals(string1)) {
						isCunzai = true;
					}
				}

				Log.d("currentDirectory", ftp.currentDirectory());
				// 是不是在该文件夹下
				if (!isCunzai) {
					// 不存在该目录，则创建目录
					ftp.createDirectory(dirFileName);
				}
				// 改变路径
				ftp.changeDirectory(dirFileName);
				initProgress();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FTPIllegalReplyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FTPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			handler.sendMessage(msg);
		}
	};
}
